package com.rongshu.view.userInfo.activity;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.home.entity.UserInfo;
import com.rongshu.view.login.entity.UpLoadFile;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.rongshu.view.userInfo.iview.PerfectInfomationView;
import com.rongshu.view.userInfo.presenter.PerfectInfomationPresenter;
import com.rongshu.widget.BanyanDialog;
import com.widget.CircleImageView;
import com.widget.datapicker.builder.TimePickerBuilder;
import com.widget.datapicker.listener.OnTimeSelectChangeListener;
import com.widget.datapicker.listener.OnTimeSelectListener;
import com.widget.datapicker.view.TimePickerView;
import com.widget.dialog.BottomListDialog;
import com.widget.titlebar.ImmersionBar;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.rongshu.utils.Constant.INTENT_FUNCTIONS;
import static com.rongshu.utils.Constant.INTENT_MESSAGE;
import static com.rongshu.utils.Constant.INTENT_TITLE;

/**
 * 完善资料
 */
public class PerfectInfomationActivity extends BaseActivity<PerfectInfomationPresenter> implements PerfectInfomationView {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;//标题
    @BindView(R.id.txt_top_function)
    TextView txt_top_function;
    @BindView(R.id.iv_head_icon)
    CircleImageView iv_head_icon;
    @BindView(R.id.txt_pen_name)
    TextView txt_pen_name;//笔名
    @BindView(R.id.txtSex)
    TextView txtSex;
    @BindView(R.id.txt_birthday)
    TextView txt_birthday;
    @BindView(R.id.txt_city)
    TextView txt_city;
    @BindView(R.id.iv_bg_icon)
    ImageView iv_bg_icon;
    @BindView(R.id.edt_signature)
    EditText edt_signature;
    @BindView(R.id.top_layout)
    RelativeLayout topLayout;

    //性别选项集合
    private List<String> sex_functions = null;
    //返回相册集合
    private List<LocalMedia> selectList = new ArrayList<>();
    //request 笔名
    private final int PEN_NAME_REQUEST_CODE = 0X01;
    //request 地区
    private final int CITY_SELECT_REQUEST_CODE = 0X03;
    //日期
    private TimePickerView pvTime;
    //getIntent
    private Intent intent = null;
    //用户user_id
    private int user_id = -1;
    //用户个人信息
    private UserInfo.ResponseBean userInfo = null;
    //isHeader
    private boolean isHeader = true;
    //头像地址，背景地址
    private String header_path = null, bg_path = null;
    //上传后的地址
    private String header_url = null, bg_url = null;
    //map
    private Map<String, Object> map = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset().keyboardEnable(true);
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .statusBarAlpha(0);
        } else {
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f);
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_perfect_infomation_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new PerfectInfomationPresenter(this), this);
        //设置title
        txt_top_title.setText(R.string.perfect_infomation);
        txt_top_function.setVisibility(View.VISIBLE);
        txt_top_function.setText(R.string.save);
        //性别
        sex_functions = new ArrayList<>();
        sex_functions.add(getString(R.string.perfect_infomation_sex_man));
        sex_functions.add(getString(R.string.perfect_infomation_sex_woman));
        sex_functions.add(getString(R.string.perfect_infomation_sex_secrecy));
        //初始化日期
        initTimePicker();
        //获取意图数据
        intent = getIntent();
        user_id = intent.getIntExtra(Constant.INTENT_DATA, user_id);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getUserInfo();
    }

    /**
     * 更新用户信息
     */
    private void refreshView(UserInfo.ResponseBean userInfo) {
        if (userInfo == null) {
            return;
        }
        this.userInfo = userInfo;
        //头像
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.user_head_icon);
        Glide.with(this)
                .load(userInfo.getAvatar())
                .apply(options)
                .into(iv_head_icon);
        //背景
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.user_top_bg);
        Glide.with(this)
                .load(userInfo.getBgp())
                .apply(options)
                .into(iv_bg_icon);
        //笔名
        txt_pen_name.setText(userInfo.getBi_name());
        //性别
        txtSex.setText(userInfo.getSex());
        //生日
        txt_birthday.setText(userInfo.getBirthday());
        //地区
        txt_city.setText(userInfo.getCity());
        //简介
        String signature = userInfo.getSignature();
        if (!TextUtils.isEmpty(signature)) {
            edt_signature.setText(signature);
            edt_signature.setSelection(signature.length());
        } else {
            edt_signature.setHint("添加个人描述，让大家更好的认识你");
        }
    }

    /**
     * 获取用户资料
     */
    public void getUserInfo() {
        if (user_id == -1) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getUserInfo(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 上传头像，背景
     */
    private void uploadHeaderOrBg() {
        showLoading(true);
        Map<String, RequestBody> bodyMap = uploadImages();
        presenter.postUploadMoreFile(bodyMap);
    }

    /**
     * 完善个人信息
     */
    private void perfectInfo() {
        //笔名
        String bi_name = txt_pen_name.getText().toString();
        if (TextUtils.isEmpty(bi_name)) {
            toast("笔名不可为空");
            return;
        }
        //user_id
        int user_id = UserInfoUtils.getUserId();
        //性别
        String sex = txtSex.getText().toString();
        //生日
        String birthday = txt_birthday.getText().toString();
        //市
        String city = txt_city.getText().toString();
        //签名
        String signature = edt_signature.getText().toString();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("pseudonym", bi_name);
        map.put("sex", sex);
        map.put("birthday", birthday);
        map.put("city", city);
        //头像,背景
        UpLoadFile upLoadFile = new UpLoadFile();
        //头像
        List<String> picList = new ArrayList<>();
        picList.add(header_url);
        upLoadFile.setFile(picList);
        //背景
        upLoadFile.setBGPfile(bg_url);
        //签名
        upLoadFile.setSignature(signature);
        presenter.postUserSetPerfectInfo(user_id, bi_name, sex, birthday, city,
                Common.encryptionSign(map), upLoadFile);
        map.clear();
    }

    @OnClick({R.id.layout_back, R.id.layout_head_icon, R.id.layout_pen_name,
            R.id.layout_sex, R.id.layout_birthday, R.id.layout_area, R.id.layout_bg,
            R.id.txt_top_function})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                showKeyboard(false);
                finish();
                break;
            case R.id.layout_head_icon://头像
                isHeader = true;
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(true)
                        .isCamera(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .circleDimmedLayer(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.layout_bg:
                isHeader = false;
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(true)
                        .isCamera(true)
                        .enableCrop(true)
                        .withAspectRatio(4, 3)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.layout_pen_name://笔名 1可以 0不可以
                if (userInfo == null) {
                    return;
                }
                int is_xiugai_biname = userInfo.getIs_xiugai_biname();
                if (is_xiugai_biname == 1) {
                    BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
                    builder.setContent("笔名仅能修改一次,\n确认修改？");
                    builder.setLeft("取消");
                    builder.setRight("修改");
                    final BanyanDialog dialog = builder.create();
                    builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
                        @Override
                        public void leftClickListener() {
                            dialog.dismiss();
                        }

                        @Override
                        public void rightClickListener() {
                            jumpActivity(AlterInfomationActivity.class,
                                    getString(R.string.perfect_infomation_pen_name),
                                    getString(R.string.alert_confirm),
                                    getString(R.string.perfect_infomation_input_pen_name),
                                    PEN_NAME_REQUEST_CODE);
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else {
                    toast(getString(R.string.pen_names_can_only_be_set_once));
                }
                break;
            case R.id.layout_sex://性别
                BottomListDialog.Builder builder = new BottomListDialog.Builder(this);
                builder.setCancle(getString(R.string.cancle));
                builder.setFunctions(sex_functions);
                builder.setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Dialog dialog) {
                        String function = sex_functions.get(position);
                        txtSex.setText(function);
                        dialog.dismiss();
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
            case R.id.layout_birthday:
                pvTime.show(view);
                break;
            case R.id.layout_area:
                Intent intent = new Intent(this, CitySelectedActivity.class);
                startActivityForResult(intent, CITY_SELECT_REQUEST_CODE);
                break;
            case R.id.txt_top_function://提交
                //头像
                if (TextUtils.isEmpty(header_url)) {
                    if (userInfo != null) {
                        header_url = userInfo.getAvatar();
                    }
                }
                //背景
                if (TextUtils.isEmpty(bg_url)) {
                    if (userInfo != null) {
                        bg_url = userInfo.getBgp();
                    }
                }
                //完善资料
                perfectInfo();
                showKeyboard(false);
                break;
        }
    }

    /**
     * 准备上传的图片集合
     */
    private Map<String, RequestBody> uploadImages() {
        //list
        List<String> pathList = new ArrayList<>();

        pathList.add(isHeader ? header_path : bg_path);

        Map<String, RequestBody> bodyMap = new HashMap<>();
        if (pathList.size() > 0) {
            for (int i = 0; i < pathList.size(); i++) {
                File file = new File(pathList.get(i));
                bodyMap.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
            }
        }
        return bodyMap;
    }

    /**
     * 跳转笔名设置界面
     *
     * @param cls
     * @param title
     * @param function
     * @param message
     * @param requestCode
     */
    public void jumpActivity(Class<?> cls, String title, String function, String message, int requestCode) {
        Intent intent = new Intent(this, cls);
        intent.putExtra(INTENT_TITLE, title);
        intent.putExtra(INTENT_FUNCTIONS, function);
        intent.putExtra(INTENT_MESSAGE, message);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 成功提示
     */
    public void showSuccessMsg(String content) {
        PictureFileUtils.deleteCacheDirFile(this);
        toast(content);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接受内部activity数据
        String message = null;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: //相册返回
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //图片真实地址
                    String path = selectList.get(0).getCutPath();
                    //保存头像，背景地址
                    if (isHeader) {
                        this.header_path = path;
                    } else {
                        this.bg_path = path;
                    }
                    Glide.with(this)
                            .load(new File(path))
                            .into(isHeader ? iv_head_icon : iv_bg_icon);
                    //上传头像或背景
                    uploadHeaderOrBg();
                    break;
                case PEN_NAME_REQUEST_CODE://笔名
                    message = data.getStringExtra(INTENT_MESSAGE);
                    txt_pen_name.setText(message);
                    break;
                case CITY_SELECT_REQUEST_CODE://城市选择
                    String city = data.getStringExtra(Constant.INTENT_MESSAGE);
                    txt_city.setText(city);
                    break;
            }
        }
    }


    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                txt_birthday.setText(getTime(date));
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
                Log.i("pvTime", "onTimeSelectChanged");
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .setSubmitText(getString(R.string.complete))
                .setSubmitColor(getResources().getColor(R.color.color_3cc051))
                .setCancelColor(getResources().getColor(R.color.color_3cc051))
                .setTitleBgColor(ContextCompat.getColor(this, R.color.white_loading_color))
                .setBgColor(ContextCompat.getColor(this, R.color.white_loading_color))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.color_4a4a4a))
                .setTextColorOut(ContextCompat.getColor(this, R.color.color_666666))
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
    }

    /**
     * 日期格式转换
     *
     * @param date
     * @return
     */
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 上传头像，背景返回
     */
    @Override
    public void uploadImageResult(UpLoadImage upLoadImage, boolean isSuccess) {
        showLoading(false);
        if (upLoadImage != null && isSuccess && upLoadImage.getErrCode() == 0) {
            UpLoadImage.ResponseBean bean = upLoadImage.getResponse();
            if (bean != null) {
                List<String> picList = bean.getImgUrl();
                if (!picList.isEmpty()) {
                    if (isHeader) {//头像
                        header_url = picList.get(0);
                    } else {//背景
                        bg_url = picList.get(0);
                    }
                }
            }
        } else {
            toast(upLoadImage.getErrMsg());
        }
    }

    /**
     * 完善资料返回
     *
     * @param iNetBean
     */
    @Override
    public void onPerfectInfo(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            isHeader = false;
            header_path = null;
            header_url = null;
            bg_path = null;
            bg_url = null;
            showSuccessMsg(iNetBean.getErrMsg());
            finish();
        } else {
            toast(iNetBean.getErrMsg());
        }
    }

    /**
     * 用户信息
     *
     * @param userInfo
     */
    @Override
    public void onUserInfo(UserInfo userInfo) {
        if (userInfo.getErrCode() == 0) {
            UserInfo.ResponseBean responseBean = userInfo.getResponse();
            if (responseBean != null) {
                refreshView(responseBean);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PictureFileUtils.deleteCacheDirFile(this);
    }
}
